from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, User, Comment
from info.utils.common import login_data
from . import news_blue
from info.utils.response_code import *


# 使用蓝图
@news_blue.route('/<int:news_id>')
@login_data
def get_detail(news_id):

    # 一.用户信息
    user = g.user

    # 二.查询点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 三.查询内容详情
    try:
        news = News.query.filter_by(id=news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        abort(404)

    # 点击查看了详细信息之后此条新闻点击数+1
    news.clicks += 1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    # 四.显示收藏信息
    # 判断用户是否登录
    is_collected = False
    if user:
        # 查询第三张表中的数据
        if news in user.collection_news:
            is_collected = True

    # 五.显示评论
    comments_list = []
    try:
        comment_list = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    comment_dict_list = []
    for comment_dict in comment_list:
        comment_dict_list.append(comment_dict.to_dict())

    author = None
    is_followed = False
    if news.user_id:
        # 是否关注作者
        try:
            author = User.query.get(news.user_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        if user:
            if user in author.followers:
                is_followed = True

    data = {
        'news_dict_li': news_dict_li,
        'user': user.to_dict() if user else None,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comment_dict_list,
        'is_followed': is_followed if author else None
    }

    return render_template('news/detail.html', data=data)


# 点击收藏/取消收藏按钮的路由
@news_blue.route('/news_collect', methods=['POST'])
@login_data
def news_collect():

    user = g.user

    # 根据前端的动作，删除或添加收藏
    params_dict = request.json
    news_id = params_dict.get('news_id')
    action = params_dict.get('action')

    # 校验数据有效性
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
    # 校验action是否只有收藏和取消收藏
    if action not in ('collect', 'cancel_collect'):
        return jsonify(errno=RET.PARAMERR, errmsg='指令错误')

    news = None
    try:
        news = News.query.filter_by(id=news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')

    # 判断是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='还未登录')

    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据提交出错')
    return jsonify(errno=RET.OK, errmsg='成功')


# 评论的接口
@news_blue.route('/news_comment', methods=['POST'])
@login_data
def news_comment():
    # 获取登录信息
    user = g.user

    # 获取参数
    parmas_dict = request.json
    news_comment = parmas_dict.get('comment')
    news_id = parmas_dict.get('news_id')
    parent_id = parmas_dict.get('parent_id')

    # 校验参数
    if not all([news_comment, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')

    # 逻辑处理
    # 1.判断是否已登录
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg='请先登录')

    # 2.创建comments模型对象,添加数据
    comment = Comment()
    comment.content = news_comment
    comment.user_id = user.id
    comment.news_id = news_id
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    # 返回ok
    return jsonify(errno=RET.OK, errmsg='成功', data=comment.to_dict())


# 关注，取消关注
@news_blue.route('/followed_user', methods=['POST'])
@login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='未登录')

    # 获取参数
    params = request.json
    author_id = params.get('user_id')
    action = params.get('action')

    # 数据有效性
    if not all([author_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺少')
    # action是否符合
    if action not in ['follow', 'unfollow']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询作者的followers中有没有user
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')
    print('author.followers')

    if user in author.followers:
        # 点击取消关注
        author.followers.remove(user)
    else:
        author.followers.append(user)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    return jsonify(errno=RET.OK, errmsg='ok')
